package io.gitee.yiwyn;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ExecutorDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        List<CompletableFuture<Integer>> tasks = new ArrayList<>();


        for (int i = 0; i < 10; i++) {
            int finalI = i;
            tasks.add(CompletableFuture.supplyAsync(() -> {
                System.out.println("执行");
                return finalI;
            }));
        }

//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            System.out.println(Thread.currentThread().getName() + "返回111");
//            return 111;
//        });


        CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).whenComplete((unused, throwable) -> {
            if (throwable != null) {
                System.out.println("开始进行异常处理");
                System.out.println("异常类型:" + throwable.getMessage());
            }

            for (CompletableFuture<Integer> task : tasks) {
                Integer now = task.getNow(0);
                System.out.println(now);
            }
        }).join();


        System.out.println("complete");

    }
}
